import os
import time
import datetime
import subprocess


def cur_time_str():
    now = datetime.datetime.now()
    time_str = now.strftime("%Y-%m-%d %H:%M:%S")
    return time_str


def get_cur_softirq_map():
    field_count = os.cpu_count() + 1
    result = subprocess.run(
        ['cat', '/proc/softirqs'],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    arr = result.stdout.split('\n')
    softirq_map = {}
    del arr[0]

    for item in arr:
        fields = []
        arr1 = item.split(' ')
        for item1 in arr1:
            if len(item1) > 0:
                fields.append(item1)
        if len(fields) == 0:
            continue
        fields = fields[0:field_count]
        softirq_map[fields[0]] = fields[1:]
    return softirq_map


def delta_softirq_map(map1, map2):
    new_map = {}
    for key in map1:
        if key not in map2:
           continue 
        delta_list = [] 
        for i in range(len(map1[key])):
            delta_list.append(int(map1[key][i]) - int(map2[key][i]))
        new_map[key] = delta_list
    return new_map


if __name__ == '__main__':
    last_map = get_cur_softirq_map() 
    while True:
        time.sleep(1)
        print('{}:'.format(cur_time_str()))
        now_map = get_cur_softirq_map() 
        delta_map = delta_softirq_map(now_map, last_map)
        for key in delta_map: 
            print('{:<10} {}'.format(key, delta_map[key]))
        print('')
        last_map = now_map

